// 手搓 compose 洋葱模型的实现 常考
let middleware = []

middleware.push(function (ctx, next) {
  console.log(1);
  next()
  console.log('end1');
})

middleware.push(function (ctx, next) {
  console.log(2);
  next()
  console.log('end2');
})

middleware.push(function (ctx, next) {
  console.log(3);
  next()
  console.log('end3');
})

function compose(middleware) {
  function dispatch(i) {
    if (i === middleware.length) return
    let fn = middleware[i]
    const next = () => {
      dispatch(i + 1)
    }
    fn(this, next)
  }

  dispatch(0)
}

compose(middleware)    // 1 2 3 end3 end2 end1